import { useAuthStore, useChatStore } from "@/store";
import { API_BASE_URL } from "@/constant/env";
import Router from "next/router";
import { inNestedIframe } from '@/utils/utils';
import { Toast } from 'antd-mobile'

const TIME_OUT_MS = 30000;
export const ControllerPool = {
  controllers: {} as Record<string, AbortController>,

  addController(
    sessionIndex: number,
    messageIndex: number,
    controller: AbortController,
  ) {
    const key = this.key(sessionIndex, messageIndex);
    this.controllers[key] = controller;
    return key;
  },

  stop(sessionIndex: number, messageIndex: number) {
    const key = this.key(sessionIndex, messageIndex);
    const controller = this.controllers[key];
    console.log(controller);
    controller?.abort();
  },

  remove(sessionIndex: number, messageIndex: number) {
    const key = this.key(sessionIndex, messageIndex);
    delete this.controllers[key];
  },

  key(sessionIndex: number, messageIndex: number) {
    return `${sessionIndex},${messageIndex}`;
  },
};

type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE";

export interface IRequset {
  method: HTTPMethod;
  token?: string;
  body?: BodyInit | any;
}

export interface IResponse {
  status: number;
  message: string;
  [index: string]: any;
}
const errorMessage = (status: number) => {

  switch (status) {
    case 400:
      return "请求参数有误，请检查请求参数或请求头！";
    case 401:
      return "请先登录或者验证身份！";
    case 403:
      return "您没有权限进行此操作！";
    case 404:
      return "该页面不存在，请检查输入的URL是否正确！";
    case 500:
      return "服务器出现了内部错误，请联系管理员。服务器出现了内部错误，请联系管理员！";
    default:
      return "未知错误";
  }
};
function catchError(error: unknown): asserts error is Error {
  if (!(error instanceof Error)) {
    throw new Error('不是一个错误对象');
  }
}
async function request<T>(
  endpoint: string,
  { method, token, body }: IRequset,
): Promise<T> {
  const authStore = useAuthStore.getState();
  const chatStore = useChatStore.getState();

  const headers: HeadersInit = {
    "Content-Type": "application/json",
  };

  if (authStore.token) {
    headers.Authorization = `${authStore.token}`;
  }
  try {
    chatStore.setLoading(true);
    const response = await fetch(`${API_BASE_URL}${endpoint}`, {
      method,
      headers,
      body: body ? JSON.stringify(body) : undefined,
    });
    chatStore.setLoading(false);
    if (!response.ok) {
      const errMessage = errorMessage(response.status);
      if (response.status === 401) {
        if (inNestedIframe()) {
          Toast.show({
            icon: 'fail',
            content: '服务器异常，请刷新重试',
          })
        } else {
          Toast.show({
            icon: 'fail',
            content: errMessage,
          })
          authStore.clearAuth();
          Router.replace("/login");
        }
      }
      if (response.status === 500) {
        throw new Error(errMessage);
      }
      throw new Error(errMessage);
    }
    const responseJson = await response.json();
    if (responseJson.status !== 200) {
      throw new Error(responseJson.message);
    }
    return responseJson.data;
  } catch (error: unknown) {
    catchError(error);
    Toast.show({
      icon: 'fail',
      content: error.message,
    })
    return Promise.reject(error.message);
  }
}

export default request;
